import conf from "../config.js";
import Request from "luch-request";

// 创建请求实例的工厂函数
const createHttpInstance = (baseURL) => {
  const instance = new Request();
  
  // 基础配置
  instance.setConfig(config => ({
    ...config,
    baseURL,
    header: {
      "Content-Type": "application/json;charset=UTF-8",
    },
    timeout: 50000
  }));

  // 统一的请求拦截器
  instance.interceptors.request.use(
    config => {
      uni.showLoading({
        title: '加载中...',
        mask: true
      });
      return config;
    },
    error => Promise.reject(error)
  );

  // 统一的响应拦截器
  instance.interceptors.response.use(
    response => {
      uni.hideLoading();
      
      const { code, data, msg } = response.data;
      
      if (code === 200) {
        return data || response.data;
      }
      
      if (code === 401) {
        handleUnauthorized();
        return;
      }
      
      uni.showToast({
        title: msg,
        icon: "none",
        duration: 2000
      });
      return;
    },
    error => {
      uni.hideLoading();
      handleRequestError(error);
      return Promise.reject(error);
    }
  );

  return instance;
};

// 处理未授权情况
const handleUnauthorized = () => {
  uni.clearStorageSync();
  uni.showToast({
    title: "登录失效,请登录",
    icon: "none",
    duration: 2000
  });
  
  setTimeout(() => {
    uni.navigateTo({ url: '/pagesB/login/login' });
  }, 1500);
};

// 处理请求错误
const handleRequestError = (error) => {
  console.log('error:',error)
  if (error.statusCode === 500) {
    uni.showToast({
      title: error.data.message||"服务端出现错误！",
      icon: "none",
      duration: 2000
    });
  } else if (error.errMsg?.trim() === "request:fail") {
    uni.showToast({
      title: "网络异常！",
      icon: "none",
      duration: 2000
    });
  }
};

// 创建不同域名的请求实例
const http = createHttpInstance(conf.baseApi);
const tempHttp = createHttpInstance(conf.tempApi);

export { http, tempHttp };